const path = require('path');
const fsPromise = require('fs-promise');
const colors = require('colors-console');
const sleep = require('../lib/sleep.js');
let configInit = false;

const defaultConfig = {
    'version': 'v2.0',
    'clientServerPort': 3000,
    'manageServerPort': 3001,
    'clientCORS': true,
    'wwwPath': 'www',
    'prefixHTTPList': [],
    'CacheSave': {
        'state': true,
        // 缓存到文件
        'CacheSaveFile': true,
        // 缓存到数据库
        'CacheSaveDB': false
    },
    // v2.0版 试用令牌 2022-12-15 ~ 2023-03-01
    'WinUIAuth': '89c95fec3ebd59abeecd7353f8d744515177d6ebb92ccaf2c71d01cc050478a70b4564c6d939b8ffb5b8c2f5b7b55fb55f3e4e42f205d09c170f37fac1e71a2ec3ce789fbb7724369422d1ec4a1db59ca5428bd9dec8fdcc7398aad330d88081d6651cdbba5b82b1aa3cd35c81f5155a998c52251548e859a7c7e4f1320c5af7377364b574228fc8804db14f0bc0d497aed1e5d67a7ef727de69e595c27f496927c79b1a3e37a2d9c44243b0926d8fb11434e8810e5eadc31f3e8f1dd583bed9bec9fc1824f9053766bc0ce4ce77f66c3c66f85dcb1b3235660fcb6abe61468a29ffc22b6dcf1d70e3531fe78ebf41f534d4c9ac42c0339e6194bd2a745d29eebfe8ede3cb4cfaa2692cd980eb148a2b656e3932484e27f8d13986a4348a514347d89735eb2f651ad25fa598b968b770d7ad13fb8195cc3a290997fa2d05574afbb939469d9e58362b3bfec05290d99e197caf9dd4048ab974ac78a68c79b4ab723d0e8e399abb3ec8a04f9f7be93a5a92596017f56a7dd20d305a597829ae197a593e76a230a380ff104201df3a52cdea655058493243698c7d614cf5a25e1a034af1a9473f1e3f11acc3bcc0df09b52e0128c468b9a1fa7e61714476b44e0143eb9599813455b307d715da22a1476e85936913d42c1a302c9b2fc89785c385b633d91b0479a44e6534c66d3c92bfe2ea1b1a6bcdf4f430dbe5030afe566f2d'
};

const configTool = {
    appBasePath: '',
    wwwPath: '',
    config: {} as any,
    async editConfig(key: string, value: any) {
        await this.init();
        let result = false;
        if (typeof this.config[key] === typeof value) {
            this.config[key] = value;
            await fsPromise.writeJSON(path.join(this.appBasePath, '/conf/config.json'), this.config);
            result = true;
        }
        return result;
    },
    async init() {
        return new Promise(async (resolve, reject) => {
            if (!configInit) {
                configInit = true;

                // 是否处于开发环境
                let isDev = !__dirname.includes('snapshot');

                if (isDev) {
                    this.appBasePath = path.join(__dirname, '../../');
                } else {
                    this.appBasePath = path.dirname(process.execPath);
                }

                await fsPromise.ensureDir(path.join(this.appBasePath, '/conf'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/fileOut'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/fileDB'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/temp/logs/http'));
                await fsPromise.ensureDir(path.join(this.appBasePath, '/www'));

                let configFile = path.join(this.appBasePath, '/conf/config.json');

                // 判断是读取配置文件
                await fsPromise.readJson(configFile).then((d: any) => {
                    if (d.version === defaultConfig.version) {
                        this.config = d;
                    } else {
                        console.log(colors('red', '----|||配置文件版本过低，重置配置文件|||----'));
                        throw new Error('配置文件版本不匹配');
                    }
                }).catch(() => {
                    // 新生成一份配置文件
                    this.config = defaultConfig;
                    fsPromise.writeJSON(configFile, this.config);
                });

                this.wwwPath = path.join(this.appBasePath, this.config.wwwPath);
            }

            while (!configInit) {
                await sleep(50);
            }
            resolve(true);
        });

    },
    preservableONDB() {
        return this.config.CacheSave.state && this.config.CacheSave.CacheSaveDB;
    },
    preservableONFile() {
        return this.config.CacheSave.state && this.config.CacheSave.CacheSaveFile;
    }
};


export = configTool;
